//
// Created by Zsir on 2025/7/25.
//

#include "Thread.h"
#include "threadPool.h"
#include "Task.h"

Thread::Thread(threadPool *pool)
    : pool_(pool),
      running_(false)
{}

void Thread::start()
{
    running_ = true;
    pthread_create(&threadId_, nullptr, &Thread::run, this);
}

void Thread::stop()
{
    if (running_)
    {
        running_ = false;
        pthread_join(threadId_, nullptr);
    }
}

void *Thread::run(void *arg)
{
    Thread *thread = (Thread *) arg;
    while (thread->running_)
    {
        auto task = thread->pool_->getTask();
        if (task.getFunc() == nullptr) break; // 如果是空任务，退出线程
        task.run();
    }
    return nullptr; // pthread要求返回值
}

Thread::~Thread()
{
    stop();
}
